<?php 
	require_once('../params.inc');
	require_once('../utils.inc');
	require_once('sf.inc');

	$name = $par->get('name');
	$thisCat = new Category($name);
	$tname = $thisCat->tableName();
	$editLink = $thisCat->editLink();
	$addLink = $thisCat->addLink();
	$from = $par->exist('from') ? $par->get('from') : 0;
	

	$path = array(
		array('Главная','index.php'),
		$thisCat->descr()
	);
	
	require_once('header.inc'); 
?>


<table width=100% height=100%>
	<tr>
		<td>
			<div id=tabButtons></div>
		</td>
	</tr>
	<tr height=100% valign=top>
		<td>
			<div id=tabs>	
				<div id=view>
					<table width=100% height=100%>
						<tr height=100%>
							<td width=100%>
			
			
<?php
	function strSplit($s) {
		$a = array();
		$len = strlen($s);
		for ($i=0; $i<$len; ++$i) {
			$a[] = $s[$i];
		}
		return $a;
	}

	function str2num($s) 
	{
		$chars = strSplit($s);
		$sz = count($chars);
		$numstr = '';
		for ($i=0; $i<$sz; ++$i) {
			if (!empty($numstr)) {
				$numstr .= '|';
			}
			$numstr .= ord($chars[$i]);
		}
		return $numstr;
	}
	
	function num2str($s) 
	{
		$chars = explode('|', $s);
		$sz = count($chars);
		$str = '';
		for ($i=0; $i<$sz; ++$i) {
			$str .= chr($chars[$i]);
		}
		return $str;
	}
	
	if ($par->exist('convert')) {
		$nm = $par->get('convert');
		$par->set($nm, str2num($par->get($nm)));
		$par->remove('convert');
	}
	
	$target = urlencode($par->href());
	
	$conv = new SysConverter($name);

	require_once('../grid.inc');
	
	$q = new Select($db, $tname);
	
	if ($par->exist('filter')) {
		$sysFilter = new DecodedFieldValues( $par->get('filter') );
		foreach ($sysFilter->asArray() as $fnm => $val) 
		{
			$q->where($fnm, $conv->convert($fnm,$val));
		}
	}
	
	$userFilterExist = false;
	if ($par->exist('userfilter')) {
		$userFilter = new DecodedFieldValues( num2str($par->get('userfilter')) );
		foreach ($userFilter->asArray() as $fnm => $val) 
		{
			$q->where($fnm, $conv->convert($fnm,$val));
		}
		$userFilterExist = true;
	}
	
	$userSortExist = false;
	if ($par->exist('sort')) {
		$userSort = new DecodedFieldValues( $par->get('sort') );
		foreach ($userSort->asArray() as $fnm => $val) {
			$q->order($fnm, $val);
		}
		$userSortExist = true;
	}
	
	$search = null;
	if ($par->exist('search')) {
		$search = num2str($par->get('search'));
	}
	
	$grid = new Grid(getHrefWithout('sort'), SHOW_REC_ON_PAGE);
	
	if ($thisCat->canEdit()) {
		$grid->addFakeColumn(
			'',
			"<button class=pict onclick=\"go('$editLink?name=$name&target=$target&keys={KEYPARAMS}')\")>" .
				"<img alt='Редактировать' src='img/edit.gif'/>".
			"</button>"
		);
	}
	
	if ($thisCat->canDel()) 
	{
		$delLink = new Url($thisCat->delLink());
		$delLink->setParam('del', 1);
		
		$grid->addFakeColumn(
			'',
			"<button class=pict onclick=\"verify('" . $delLink->__toString() . "&name=$name&target=$target&keys={KEYPARAMS}','Вы уверены что хотите удалить запись?')\">".
				"<img alt='Удалить' src='img/delete.gif'/>".
			"</button>"
		);
	}				
	
	$searchWhereString = '';
	$fields = new Fields($name);
	$fields->open();
	
	while ($fields->fetch()) 
	{
		if ($fields->isKey() || $fields->isViewable()) {
			$fieldPos = 0;
								
			if ($fields->isKey()) {
				$fieldPos = $q->addFields($fields->name())-1;
				$grid->addKeyField(
					$fieldPos,
					$fields->name(),
					$fields->type()
				);
			}
			
			if ($fields->isViewable()) {
				if ($fields->type() == FIELD_TYPE_FAKE) {
					$grid->addFakeColumn(
						$fields->descr(),
						$fields->fmt(),
						$fields->size() ? ($fields->size().'%') : 0
					);
				}
				else {
					$fieldPos = resolveDict($q, $name, $fields->nameInSelect(), $fields->isNullAllowed())-1;
					$grid->addColumn(
						$fieldPos,
						$fields->name(),
						$fields->descr(),
						"<p style='" . $fields->style() . ";'>{VALUE}</p>",
						$fields->size() ? ($fields->size().'%') : 0
					);
				}
				
				if (!is_null($search) && ($fields->type()==FIELD_TYPE_STRING || $fields->type()==FIELD_TYPE_TEXT)) {
					if (!empty($searchWhereString)) {
						$searchWhereString .= ' OR ';
					}
					$searchWhereString .= ($fields->name() . " LIKE CONCAT('%'," . $db->quote($search) . ",'%')");
				}
			}
		}
		
		if ($fields->isFiltered()) {
			$q->where($fields->name(), $fields->filter());
		}
		
		if ($fields->isSorted() && !$userSortExist) {
			$q->order($fields->name(), ($fields->sort() == 'A' ? ASC : DESC));
		}
	}
	$q->addWhereString($searchWhereString);
	$q->setSkip($from);
	$sql = $q->run();
	
	if (!is_null($search)) {
		$grid->addProcessor( 
			new WordReplaceProcessor(
				$search, 
				"<span style='color:red;'>$search</span>"
			) 
		);
	}

	$grid->create($q);
	$showedCount = $grid->render();
	
	$sql = preg_replace('/LIMIT [0-9,]*/i', '', $sql);
	$sql = preg_replace('/SELECT[ ]*.+[ ]*FROM/i', 'SELECT NULL FROM', $sql);
	
	$countAllRecords = DB::countRecords($sql);
	
	$fromRecord = $countAllRecords ? ($from+1) : 0;
	$toRecord = $countAllRecords ? ($fromRecord + $showedCount - 1) : 0;
	
	$currPage = ceil(($from + $showedCount) / SHOW_REC_ON_PAGE);
	$countAllPages = ceil($countAllRecords / SHOW_REC_ON_PAGE);
?>

							</td>
						</tr>
						<tr>
							<td>
								<table cellpadding=1>
									<tr>
										<?php
											if ($thisCat->canAdd()) {
												echo "<td><button onclick=\"go('$addLink?name=$name&target=$target')\">Добавить</button></td>";
											}
										?>
										<td>
											<div class=btndelim></div>
										</td>
										<td>
											<button onclick="go('<?php echo getHrefWithModified('from',0);?>')">&lt;&lt;&nbsp;В начало</button>
										</td>
										<td>
											<button id=back onclick="go('<?php echo getHrefWithModified('from',$from-SHOW_REC_ON_PAGE);?>')">&lt;&nbsp;Предыдущие <?php echo SHOW_REC_ON_PAGE ?></button>
										</td>
										<td>
											<button id=forth onclick="go('<?php echo getHrefWithModified('from',$from+SHOW_REC_ON_PAGE);?>')">Следующие <?php echo SHOW_REC_ON_PAGE ?>&nbsp;&gt;</button>
										</td>
									</tr>
								</table>
								<div style="text-align:right; color:gray; ">
									<?php echo "Записи $fromRecord - $toRecord из $countAllRecords • Страница $currPage из $countAllPages" ?>
								</div>
							</td>
						</tr>
					</table>
				</div>
				
				
				<div id=sort>
					<style>
						#sel_left, #sel_right {	width: 100%;}
						#up, #down, #on, #off { width: 50px; }
					</style>

	
					<table width=100%>
						<tr>
							<td>
								<button id=up onclick="up()" title='Поле вверх'>/\</button><br>
								<button id=down onclick="down()" title='Поле вниз'>\/</button><br>
							</td>
							<td width=50%>
								Сортировки:
								<select id=sel_left size=10 multiple onchange="onSelect()"></select>
							</td>
							<td>
								<button id=on onclick="on()" title='Добавить поле'>&lt;</button><br>
								<button id=off onclick="off()" title='Убрать поле'>&gt;</button><br>
							</td>
							<td width=50%>
								&nbsp;
								<select id=sel_right size=10 multiple onchange="onSelect()"></select>
							</td>
						</tr>
						<tr>
							<td></td>
							<td>
								Упорядочить по 
								<select id=dir size=1 onchange="setDirection()">
									<option value=0>по возрастанию
									<option value=1>по убыванию
								</select>
							</td>
							<td></td>
							<td></td>
						</tr>
					</table>
					
					<div align=right>
						<table>
							<tr>
								<td>
									<button id=clearSort disabled onclick="clearSort()">Удалить все</button>
								</td>
								<td>
									<div class=btndelim></div>
								</td>
								<td>
									<button id=sortOk onclick="applySort()">Применить</button>
								</td>
							</tr>
						</table>
					</div>

					
					
					<script lang=javascript>
						var
							selLeft = document.getElementById('sel_left'),
							selRight = document.getElementById('sel_right'),
							btnUp = document.getElementById('up'),
							btnDown = document.getElementById('down'),
							btnOn = document.getElementById('on'),
							btnOff = document.getElementById('off'),
							selDir = document.getElementById('dir'),
							sortOk = document.getElementById('sortOk');
						
						function addSort(text, val, dir) {
							var oOption = new Option(text, val);
							oOption.setAttribute('dir',dir);
							selLeft.options[selLeft.options.length] = oOption;
						}
							
						function addNoSort(text, val) {
							selRight.options[selRight.options.length] = new Option(text, val);
						}
							
						function move(oFrom, oTo) {
							var i = 0;
							while (i < oFrom.options.length) {
								if (oFrom[i].selected) {
									var opt = new Option(oFrom[i].text, oFrom[i].value);
									opt.setAttribute('dir',0);
									oTo.options[oTo.options.length] = opt;
									oFrom.options[i] = null;
									i = 0;
								}
								else {
									++i;
								}
							}
							update();
						}
						
						function swap(oOpt1, oOpt2) {
							var text = oOpt2.text, 
								value = oOpt2.value, 
								selected = oOpt2.selected, 
								dir = oOpt2.getAttribute('dir');
								
							oOpt2.text = oOpt1.text;
							oOpt2.value = oOpt1.value;
							oOpt2.selected = oOpt1.selected;
							oOpt2.setAttribute('dir', oOpt1.getAttribute('dir'));
							oOpt1.text = text;
							oOpt1.value = value;
							oOpt1.selected = selected;
							oOpt1.setAttribute('dir', dir);
							
							update();
						}
						
						function on() {
							move(selRight, selLeft);
						}
						
						function off() {
							move(selLeft, selRight);
						}
						
						function up() {
							swap( 
								selLeft.options[selLeft.selectedIndex], 
								selLeft.options[selLeft.selectedIndex-1]
							);
						}
						
						function down() {
							swap( 
								selLeft.options[selLeft.selectedIndex], 
								selLeft.options[selLeft.selectedIndex+1]
							);
						}
						
						function setDirection() {
							if (selLeft.selectedIndex >= 0) {
								selLeft.options[selLeft.selectedIndex]
									.setAttribute('dir', selDir.selectedIndex);
							}
						}
					
						function update() {
							btnUp.disabled = selLeft.selectedIndex <= 0;
							btnDown.disabled = (selLeft.selectedIndex < 0 || selLeft.selectedIndex >= selLeft.options.length-1);
							btnOn.disabled = (!selRight.options.length || selRight.selectedIndex < 0);
							btnOff.disabled = (!selLeft.options.length || selLeft.selectedIndex < 0);
							selDir.disabled = selLeft.selectedIndex < 0;
							selDir.selectedIndex = 
								(selLeft.selectedIndex < 0) ? 
									-1 :
									selLeft.options[selLeft.selectedIndex].getAttribute('dir');
							sortOk.disabled = 0;
						}
						
						function onSelect() {
							update();
						}
						
						function getSortUrlPath() {
							var url = new String;
							for (var i=0; i<selLeft.options.length; ++i) {
								if (url.length) {
									url += '@';
								}
								url += (selLeft.options[i].value + '=' + (selLeft.options[i].getAttribute('dir')!=0 ? 'DESC':'ASC'));
							}
							return url;
						}
						
						function applySort() {
							var sort = getSortUrlPath();
							if (sort.length) {
								go('<?php echo getHrefWithout('sort')?>sort=' + getSortUrlPath());
							}
							else {
								go('<?php echo getHrefWithout('sort')?>');
							}
						}
						
						function clearSort() {
							go('<?php echo getHrefWithout('sort')?>');
						}
						
						
						<?php
							if ($userSortExist) {
								$sorts = $userSort->asArray();
								foreach ($sorts as $fnm => $val) {
									$f = new Fields($name, $fnm);
									$f->open();
									$f->fetch();
									echo "addSort('" . $f->descr() . "','" . $f->name() ."'," . 
												($userSort->getValueOf($f->name())==ASC ? '0':'1') . ");";
								}
								$fields->reset();
								while ($fields->fetch()) {
									if ($fields->isViewable() && !isset($sorts[$fields->name()])) {
										echo "addNoSort('" . $fields->descr() . "','" . $fields->name() ."');";
									}
								}
							}
							else {
								$fields->reset();
								while ($fields->fetch()) {
									if ($fields->isViewable()) {
										if ($fields->isSorted()) {
												echo "addSort('" . $fields->descr() . "','" . $fields->name() ."'," . 
														($fields->sort()=='A' ? '0':'1') . ");";
										}
										else {
											echo "addNoSort('" . $fields->descr() . "','" . $fields->name() ."');";
										}
									}
								}
							}
						?>
						
						update();
						sortOk.disabled = 1;
						
						<?php
							if ($userSortExist) {
								echo "document.getElementById('clearSort').disabled = false;";
							}
						?>
					</script>					
				</div>
				
				
				<div id=filter>
					<script lang=javascript>
						var userFilters = new Object();
						
						function flipFilter(fname, bOn) {
							document.getElementById('filter_set_' + fname).checked = bOn;
							document.getElementById('filter_'+fname).style.visibility = (bOn ? 'visible' : 'hidden');
							
							if (bOn) {
								userFilters[fname] = 1;
							}
							else {
								delete userFilters[fname];
							}
						}
						
						function getFilterUrlPath() {
							var url = new String;
							for (var fname in userFilters) {
								if (url.length) {
									url += '@';
								}
								url += (fname + '=');
								url += (window['filter_'+fname].isNull()==true) ? '' : window['filter_'+fname].value();
							}
							return url;
						}
						
						function applyFilters() {
							var url = getFilterUrlPath();
							if (url.length) {
								go(
									'<?php echo getHrefWithout('userfilter')?>',
									{'name':'userfilter', 'value': url}, 
									{'name':'convert', 'value': 'userfilter'}
								);
							}
							else {
								go('<?php echo getHrefWithout('userfilter')?>');
							}
						}
						
						function clearFilters() {
							go('<?php echo getHrefWithout('userfilter')?>');
						}
					</script>
								
					<table width=100%>
						<?php
							$filters = array();
							if ($userFilterExist) {
								$filters = $userFilter->asArray();
							}
							$fields->reset();
							while ($fields->fetch()) {
								if ($fields->isViewable() && $fields->isFilterAllowed()) {
									$ctl = null;
									$ctlName = 'filter_'.$fields->name();
									
									$dict = new Dictionary($name, $fields->name());
									if ($dict->exist()) {
										$ctl = new DictEditControl($ctlName, $fields->isNullAllowed(), false);
										$ctl->create(
											$dict->getName(),
											$dict->getKeyFieldName(),
											$dict->getValueFieldName(),
											$dict->getConditions()
										);
									}
									else {
										switch ($fields->type()) {
											case FIELD_TYPE_STRING:
												$ctl = new StringEditControl($ctlName, $fields->length(), false, false);
												break;
											case FIELD_TYPE_INTEGER:
												$ctl = new IntegerEditControl($ctlName, $fields->length(), false, false);
												break;
											case FIELD_TYPE_DATETIME:
												$ctl = new DateTimeEditControl($ctlName, false, false);
												break;
											case FIELD_TYPE_DATE:
												$ctl = new DateEditControl($ctlName, false, false);
												break;
											default:
												die("Invalid field type [" . $fields->type() . "] is specified for filter");
										}
									}
									
									if (isset($filters[$fields->name()])) {
										$ctl->setValue( $filters[$fields->name()] );
									}
							
									$txt = <<<EOD
										<tr>
											<td>
												<input type=checkbox id="filter_set_{NAME}" onclick="flipFilter('{NAME}',this.checked)"/> 
											</td>
											<td align=right nowrap>
												{DESCR}
											</td>
											<td>&nbsp;=&nbsp;</td>
											<td nowrap width=100%>
												{CONTROL}
												<script>
													flipFilter('{NAME}',{EXIST});
												</script>
											</td>
										</tr>
EOD;
									echo
										str_replace(
											array('{NAME}', '{DESCR}', '{CONTROL}', '{EXIST}'),
											array(
												$fields->name(), 
												$fields->descr(), 
												$ctl->render(), 
												isset($filters[$fields->name()]) ? 'true' : 'false'
											),
											$txt
										);
								}
							}
						?>
					</table>
					
					<div align=right>
						<table>
							<tr>
								<td>
									<button id=clearFilters disabled onclick="clearFilters()">Удалить все</button>
								</td>
								<td>
									<div class=btndelim></div>
								</td>
								<td>
									<button onclick="applyFilters()">Применить</button>
								</td>
							</tr>
						</table>
					</div>
					
					<script lang=javascript>
						<?php
							if ($userFilterExist) {
								echo "document.getElementById('clearFilters').disabled = false;";
							}
						?>
					</script>
						
				</div>
				
				<div id=search>
					Искать: 
					<?php
						$ctl = new StringEditControl('searchString', 255, false, false);
						$ctl->setValue($search);
						echo $ctl->render();
					?>

					<div align=right>
						<table>
							<tr>
								<td>
									<button id=clearSearch disabled onclick="clearSearch()">Удалить</button>
								</td>
								<td>
									<div class=btndelim></div>
								</td>
								<td>
									<button onclick="applySearch()">Применить</button>
								</td>
							</tr>
						</table>
					</div>
					
					<script lang=javascript>
						function applySearch() {
							var search = window['searchString'].value();
							if (search.length) {
								go(
									'<?php echo getHrefWithout('search')?>',
									{'name':'search', 'value': search}, 
									{'name':'convert', 'value': 'search'}
								);
							}
							else {
								go('<?php echo getHrefWithout('search')?>');
							}
						}
						
						function clearSearch() {
							go('<?php echo getHrefWithout('search')?>');
						}
						
						<?php
							if (!is_null($search)) {
								echo "document.getElementById('clearSearch').disabled = false;";
							}
						?>
					</script>
				</div>
			</div>
		</td>
	</tr>
</table>
		
		<script lang=javascript>
			document.getElementById('back').disabled = 
				new Number('<?php echo $from;?>').valueOf() ? false : true;
				
			document.getElementById('forth').disabled = 
				new Number('<?php echo $q->eof();?>').valueOf() ? true : false;
		</script>
		
<script lang=javascript>
	window.oTabs = new sea.Tabs(document.getElementById('tabButtons'), document.getElementById('tabs'));
	oTabs.add('Просмотр',document.getElementById('view'));
	
	var sortTabName = 'Сортировки';
	<?php
		if ($userSortExist) {
			echo "sortTabName += ' [" . $userSort->count() . "]';";
		}
	?>	
	oTabs.add(sortTabName,document.getElementById('sort'));
	
	var filterTabName = 'Фильтры';
	<?php
		if ($userFilterExist) {
			echo "filterTabName += ' [" . $userFilter->count() . "]';";
		}
	?>
	oTabs.add(filterTabName,document.getElementById('filter'));
	
	var searchTabName = 'Поиск';
	<?php
		if (!is_null($search)) {
			echo "searchTabName += ' [" . ellipsis($search, 5) . "]';";
		}
	?>
	oTabs.add(searchTabName,document.getElementById('search'));
	
	oTabs.create();
</script>

<?php require_once('footer.inc'); ?>